package com.qjdchina.sku.biz.impl;

import java.math.BigDecimal;
import java.util.*;

import com.qjdchina.sku.biz.*;
import com.qjdchina.sku.dao.mapper.*;
import com.qjdchina.sku.model.*;
import com.qjdchina.sku.model.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.qjdchina.commons.enums.IsDeleted;
import com.qjdchina.commons.model.PageModel;
import com.qjdchina.commons.result.Result;
import com.qjdchina.sku.converter.ProductSetConverter;
import com.qjdchina.sku.converter.SkuProductConverter;
import com.qjdchina.sku.model.query.ProductSetQueryVO;
import com.qjdchina.sku.service.enums.SkuResultCode;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ProductSetManagerImpl implements ProductSetManager {
	@Autowired
	private ProductSetMapper productSetMapper;
	@Autowired
	private SkuProductMapper skuProductMapper;
	@Autowired
	private ProductSetComponentMapper productSetComponentMapper;
	@Autowired
	private CategoryManager categoryManager;
	@Autowired
	private BrandManager brandManager;
	@Autowired
	private HardcoverStandardManager hardcoverStandardManager;

	@Autowired
	private CategoryMapper categoryMapper;

	@Autowired
	private BrandMapper brandMapper;

	@Autowired
	private HardcoverStandardMapper hardcoverStandardMapper;

	@Autowired
	private SkuItemManager skuItemManager;

	@Autowired
	private RelProductSkuAttributeMapper relProductSkuAttributeMapper;

	/**
	 * 根据条件分页查询项目
	 * shenpingfeng
	 * 2017年1月4日
	 * @param productSetQueryVO
	 * @param pageModel
	 * @return
	 */
	@Override
	public Result<PageModel<ProductSetVO>> queryPagedProductSetList(ProductSetQueryVO productSetQueryVO,
			PageModel<ProductSetVO> pageModel) {
		Map<String, Object> params = convertProductSetQueryVOToMap(productSetQueryVO);
		int pagedProductSetTotal = productSetMapper.getPagedProductSetTotal(params);
		List<ProductSet> productSets = productSetMapper.queryPagedProductSetList(params,pageModel);
		List<ProductSetVO> productSetVOs = ProductSetConverter.toProductSetVOs(productSets);
		pageModel.setPagedRecords(productSetVOs);
		pageModel.setTotalCount(pagedProductSetTotal);
		return new Result<PageModel<ProductSetVO>>(pageModel);
	}

	private Map<String, Object> convertProductSetQueryVOToMap(ProductSetQueryVO queryVO) {
		Map<String, Object> params = new HashMap<String, Object>();

		params.put("estateType", queryVO.getEstateType());
		params.put("hardCoverCostStart", queryVO.getHardCoverCostStart());
		params.put("hardCoverCostEnd", queryVO.getHardCoverCostEnd());

		return params;

	}
	
	/**
	 * 获取产品详情
	 * shenpingfeng
	 * 2017年1月4日
	 * @param productSetId
	 * @return
	 */
	@Override
	public Result<List<ConfigurationVO>> queryProductSetDetail(Integer productSetId) {
		if (productSetId == null) {
			return new Result<List<ConfigurationVO>>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		List<SkuProduct> skuProducts = skuProductMapper.selectProductByProductSetId(productSetId);

		List<SkuProductVO> skuProductVOs = new ArrayList<SkuProductVO>();
		for (SkuProduct skuProduct : skuProducts) {
			SkuProductVO skuProductVO = SkuProductConverter.toSkuProductVO(skuProduct);
			skuProductVO.setNumber(new BigDecimal(skuProduct.getNumber()));
			BigDecimal strategicPrice = getStrategicPrice(skuProduct);
			skuProductVO.setStrategicPrice(strategicPrice);
			skuProductVOs.add(skuProductVO);
		}
		//根据产品获取品类品牌
		for (SkuProductVO skuProduct : skuProductVOs) {
			Result<Category> resultCategory = categoryManager.getCagegorysById(skuProduct.getSkuCategoryId());
			Result<BrandVO> resultBrand = brandManager.getBrandById(skuProduct.getSkuBrandId());

			Category category = resultCategory.getDataModel();
			if (category != null) {
				String categoryName = category.getLabel();
				skuProduct.setCategoryName(categoryName);
			}
			BrandVO brandVO = resultBrand.getDataModel();
			if (brandVO != null) {
				String brandName = brandVO.getLabel();
				skuProduct.setBrandName(brandName);
			}
		}
		//获取所有精装标准
		Result<List<HardcoverStandard>> result = hardcoverStandardManager.getAllHardcoverStandard();
		List<HardcoverStandard> hardcoverStandards = result.getDataModel();
		List<ConfigurationVO> configVOs = new ArrayList<>();
		for (HardcoverStandard hardcoverStandard : hardcoverStandards) {
			ConfigurationVO configVO = new ConfigurationVO();
			configVO.setHardcoverStandard(hardcoverStandard);
			//获取关联品类
			Result<List<Integer>> resultCategoryId = hardcoverStandardManager.getCategoryIdByHardcoverStandardId(hardcoverStandard.getId
					());
			List<Integer> categoryIds = resultCategoryId.getDataModel();
			List<SkuProductVO> skuProductVOList = new ArrayList<>();
			for (SkuProductVO skuProduct : skuProductVOs) {
				Integer skuCategoryId = skuProduct.getSkuCategoryId();
				if (categoryIds.contains(skuCategoryId)) {
					skuProductVOList.add(skuProduct);
				}
			}
			configVO.setSkuProductVOs(skuProductVOList);
			configVOs.add(configVO);
		}

		return new Result<List<ConfigurationVO>>(configVOs);
	}

	@Override
	public Result<Map<String, ProductSetCompareVO>> productSetCompare(List<Integer> productSetIdList) {
		if (productSetIdList == null || productSetIdList.size() == 0) {
			return new Result<Map<String, ProductSetCompareVO>>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}

		//获取产品库信息
		List<ProductSet> productSetList = productSetMapper.selectByIds(productSetIdList);
		if (productSetList == null || productSetList.size() == 0) {
			return new Result<Map<String, ProductSetCompareVO>>(SkuResultCode.DATA_NOT_EXIST);
		}

		//获取产品库部品信息
		List<SkuProduct> skuProductList = skuProductMapper.selectProductByProductSetIds(productSetIdList);
		Map<Integer, List<SkuProduct>> productMap = new HashMap<>();
		Map<Integer, String> categoryMap = new HashMap<>();
		Map<Integer, String> brandMap = new HashMap<>();
		if (skuProductList != null && skuProductList.size() > 0) {
			Set<Integer> categoryIdSet = new HashSet<>();
			Set<Integer> brandIdSet = new HashSet<>();
			for (SkuProduct skuProduct : skuProductList) {
				categoryIdSet.add(skuProduct.getSkuCategoryId());
				brandIdSet.add(skuProduct.getSkuBrandId());
			}
			//获取品类名称映射
			List<Integer> categoryIdList = new ArrayList<>();
			categoryIdList.addAll(categoryIdSet);
			List<Category> categoryList = categoryMapper.selectByIds(categoryIdList);
			for (Category category : categoryList) {
				categoryMap.put(category.getId(), category.getLabel());
			}
			//获取品牌名称映射
			List<Integer> brandIdList = new ArrayList<>();
			brandIdList.addAll(brandIdSet);
			List<Brand> brandList = brandMapper.selectByIds(brandIdList);
			for (Brand brand : brandList) {
				brandMap.put(brand.getId(), brand.getLabel());
			}

			//封装产品库部品
			for (SkuProduct skuProduct : skuProductList) {
				List<SkuProduct> skuProducts;
				if (productMap.containsKey(skuProduct.getProductSetId())) {
					skuProducts = productMap.get(skuProduct.getProductSetId());
				} else {
					skuProducts = new ArrayList<>();
				}
				skuProducts.add(skuProduct);
				productMap.put(skuProduct.getProductSetId(), skuProducts);
			}
		}


		//获取所有精装标准
		Result<List<HardcoverStandard>> result = hardcoverStandardManager.getAllHardcoverStandard();
		List<HardcoverStandard> hardcoverStandards = result.getDataModel();
		List<Integer> hardcoverStandardIds = new ArrayList<>();
		for (HardcoverStandard hardcoverStandard : hardcoverStandards) {
			hardcoverStandardIds.add(hardcoverStandard.getId());
		}
		List<RelHardcoverStandardCategory> relHardcoverStandardCategoryList = hardcoverStandardMapper
				.selectCategoryIdsByHardcoverStandardIds(hardcoverStandardIds);
		Map<Integer, List<Integer>> hardcoverCategoryMap = new HashMap<>();
		for (RelHardcoverStandardCategory relHardcoverStandardCategory : relHardcoverStandardCategoryList) {
			List<Integer> categoryIds;
			if (hardcoverCategoryMap.containsKey(relHardcoverStandardCategory.getHardcoverStandardId())) {
				categoryIds = hardcoverCategoryMap.get(relHardcoverStandardCategory.getHardcoverStandardId());
			} else {
				categoryIds = new ArrayList<>();
			}
			categoryIds.add(relHardcoverStandardCategory.getCategoryId());
			hardcoverCategoryMap.put(relHardcoverStandardCategory.getHardcoverStandardId(), categoryIds);
		}

		//封装产品库结果
		Map<String, ProductSetCompareVO> resultMap = new HashMap<>();
		for (ProductSet productSet : productSetList) {
			ProductSetCompareVO productSetCompareVO = new ProductSetCompareVO();
			BeanUtils.copyProperties(productSet, productSetCompareVO);

			List<ConfigurationVO> configVOs = new ArrayList<>();
			for (HardcoverStandard hardcoverStandard : hardcoverStandards) {
				ConfigurationVO configVO = new ConfigurationVO();
				configVO.setHardcoverStandard(hardcoverStandard);

				List<Integer> categoryIds = hardcoverCategoryMap.get(hardcoverStandard.getId());
				List<SkuProductVO> skuProductVOList = new ArrayList<>();
				List<SkuProduct> skuProducts = productMap.get(productSet.getId());
				if (skuProducts != null) {
					for (SkuProduct skuProduct : skuProducts) {
						Integer skuCategoryId = skuProduct.getSkuCategoryId();
						if (categoryIds.contains(skuCategoryId)) {
							SkuProductVO skuProductVO = SkuProductConverter.toSkuProductVO(skuProduct);
							skuProductVO.setNumber(new BigDecimal(skuProduct.getNumber()));
							skuProductVO.setCategoryName(categoryMap.get(skuProduct.getSkuCategoryId()));
							skuProductVO.setBrandName(brandMap.get(skuProduct.getSkuBrandId()));
							BigDecimal strategicPrice = getStrategicPrice(skuProduct);
							skuProductVO.setStrategicPrice(strategicPrice);
							skuProductVOList.add(skuProductVO);
						}
					}
				}
				configVO.setSkuProductVOs(skuProductVOList);
				configVOs.add(configVO);
			}
			productSetCompareVO.setConfigurationVOList(configVOs);
			resultMap.put(String.valueOf(productSet.getId()), productSetCompareVO);
		}

		return new Result<Map<String, ProductSetCompareVO>>(resultMap);
	}

	/**
	 * 获取战略价格
	 *
	 * @param skuProduct
	 * @return
	 */
	private BigDecimal getStrategicPrice(SkuProduct skuProduct) {
		Result<Integer> strategicSkuItemIdRes = skuItemManager.getStrategicSkuItemId(skuProduct.getSkuCategoryId());
		Integer strategicSkuItemId = null;
		if (strategicSkuItemIdRes.isSuccess()) {
			strategicSkuItemId = strategicSkuItemIdRes.getDataModel();
		}
		if (strategicSkuItemId != null) {
			RelProductSkuAttribute relProductSkuAttribute = relProductSkuAttributeMapper.selectByProductIdAndSkuItemId(skuProduct
					.getProductId(), strategicSkuItemId);
			if (relProductSkuAttribute != null) {
				BigDecimal strategicPrice = StringUtils.isBlank(relProductSkuAttribute.getValue()) ? null : new BigDecimal
						(relProductSkuAttribute.getValue());
				return strategicPrice;
			}
		}
		return null;
	}

	/**
	 * 创建产品
	 * shenpingfeng
	 * 2017年1月4日
	 * @param productSetVO
	 * @return
	 */
	@Override
	@Transactional
	public Result<Integer> createProductSet(ProductSetVO productSetVO) {
		if(productSetVO == null){
			return new Result<Integer>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}

		productSetVO.setIsDeleted(IsDeleted.NO.getValue());
		productSetVO.setGmtCreated(new Date());
		productSetVO.setGmtModified(new Date());
		String code = UUID.randomUUID().toString();
		productSetVO.setCode(code);
		ProductSet productSet = ProductSetConverter.toProductSet(productSetVO);
		int row = productSetMapper.insertSelective(productSet);
		if(row == 0){
			return new Result<Integer>(SkuResultCode.ADD_FAIL);
		}
		ProductSet product = productSetMapper.getProductSetByCode(code);
		for(ProductSetComponent productSetComponent:productSetVO.getProductSetComponentList()){
			productSetComponent.setProductSetId(product.getId());
			productSetComponentMapper.insertSelective(productSetComponent);
		}

		return new Result<Integer>(product.getId());
	}
	
	/**
	 * 更新产品
	 * shenpingfeng
	 * 2017年1月5日
	 * @param productSetVO
	 * @return
	 */
	@Override
	public Result<Integer> updateProductSet(ProductSetVO productSetVO) {
		if(productSetVO == null){
			return new Result<Integer>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		List<ProductSetComponent> productSetComponents = JSON.parseArray(productSetVO.getProductList(), ProductSetComponent.class);
		ProductSet productSet = ProductSetConverter.toProductSet(productSetVO);
		int row = productSetMapper.updateByPrimaryKeySelective(productSet);
		if(row == 0){
			return new Result<Integer>(SkuResultCode.UPDATE_FAIL);
		}
		
		if(productSetComponents != null && productSetComponents.size()>0){
			for(ProductSetComponent productSetComponent:productSetComponents){
				Integer id = productSetComponent.getId();
				if(id == null){
					productSetComponent.setProductSetId(productSetVO.getId());
					productSetComponentMapper.insertSelective(productSetComponent);
				}else {
					String isDeleted = productSetComponent.getIsDeleted();
					if(StringUtils.isNotBlank(isDeleted)&&isDeleted.equals("1")){
						productSetComponentMapper.deleteByPrimaryKey(id);
					}else {
						productSetComponentMapper.updateByPrimaryKeySelective(productSetComponent);
					}	
				}	
			}
		}

		return new Result<Integer>(productSet.getId());
	}
	
	/**
	 * 删除部品
	 * shenpingfeng
	 * 2017年1月9日
	 * @param id
	 * @return
	 */
	@Override
	public Result<Integer> deleteComponent(Integer id) {
		if(id == null){
			return new Result<Integer>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		int row = productSetComponentMapper.deleteByPrimaryKey(id);
		if(row == 0){
			return new Result<Integer>(SkuResultCode.DELETE_FAIL);
		}

		return new Result<Integer>(row);
	}

	@Override
	public Result<Integer> renameProductSet(Integer productSetId, String productSetName, Integer userId) {
		ProductSet productSet = productSetMapper.selectByProductSetName(productSetName);
		if (productSet != null) {
			return new Result<Integer>(SkuResultCode.PRODUCT_LIBRARY_EXIST);
		}
		ProductSet productSetOld = productSetMapper.selectByPrimaryKey(productSetId);
		if (productSetOld == null) {
			return new Result<Integer>(SkuResultCode.PRODUCT_LIBRARY_NOT_EXIST);
		}

		ProductSetVO productSetVO = new ProductSetVO();
		BeanUtils.copyProperties(productSetOld, productSetVO);
		productSetVO.setUserId(userId);
		productSetVO.setName(productSetName);
		productSetVO.setId(null);

		List<ProductSetComponent> productSetComponentList = productSetComponentMapper.selectByProductSetId(productSetId);
		if (productSetComponentList == null || productSetComponentList.size() == 0) {
			return new Result<Integer>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		for (ProductSetComponent productSetComponent : productSetComponentList) {
			productSetComponent.setId(null);
		}
		productSetVO.setProductSetComponentList(productSetComponentList);

		Result<Integer> result = createProductSet(productSetVO);

		return result;
	}
}
